#!/usr/bin/python2.4
import sys

import urlparse
import os.path
import urllib
import pickle
import re


from optparse import OptionParser


from feedstore import feedstore
from feedprocessor import feedprocessor

def write_latest(latest, downloads):
	"""write the downloaded files to the "latest" playlist
	file. Assumes downloads is a list of tuples of
	(url, full/file/pathname)"""
	
	for d in downloads:
		latest.write("%s\r\n" % d[1])

class podgetter:
	
	def __init__(self):
		self.init_config()
		self.init_options()
		self.feedstore = feedstore()

	def init_config(self):
		self.config = {"feeds" : "./feeds", 
			  "latest" : "./latest.m3u",
			  "basedir" : "~/podcasts"}
	
	def init_options(self):
		self.optparser = OptionParser()
		self.optparser.add_option("-f", "--feed-file",
                  action="store", type="string", dest="feeds")
		self.optparser.add_option("-c", "--config-file",
                  action="store", type="string", dest="config")		

	def load_options(self):
		"""load_options - we load the command line options first, incase we're not using 			a default config file"""
		(self.options, self.args) = self.optparser.parse_args()
		

	def load_config(self):
		if self.options.config is not None:
			print "config passed"
		else:
			print "no config passed"


	
	def merge_options_config(self):
		pass
	


	def main(self):
		self.load_options()
		self.load_config()
		self.merge_options_config()
		self.feedstore.open(self.config["feeds"])
		
		downloaded = []
	
		for feed in self.feedstore.feeds():
			print feed.feedname
			fp = feedprocessor(self.config, feed)
			fp.process()
			downloaded = downloaded + fp.downloaded

		latest = file(self.config["latest"], 'w')
		write_latest(sys.stdout, downloaded)
		latest.close()



if __name__ == "__main__":
	podgetter().main()
